package com.security.it.authentication.image;

import com.security.it.core.enums.ValidateCodeType;
import com.security.it.core.properties.SecurityProperties;
import com.security.it.authentication.dto.ValidateCode;
import com.security.it.authentication.common.ValidateCodeGenerator;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import java.util.Objects;

public class ImageCodeGenerator implements ValidateCodeGenerator {

    private SecurityProperties securityProperties;

    @Override
    public ValidateCode generate(ServletWebRequest request) {
        int length = securityProperties.getCode().getImage().getLength();
        int width = ServletRequestUtils.getIntParameter(request.getRequest(), "width", securityProperties.getCode().getImage().getWidth());
        int height = ServletRequestUtils.getIntParameter(request.getRequest(),"height", securityProperties.getCode().getImage().getHeight());
        ImageVerificationCode image = new ImageVerificationCode(width, height, length);
        return new ImageCode(image.getImage(), image.getText(), securityProperties.getCode().getImage().getExpireIn());
    }

    @Override
    public boolean accept(ValidateCodeType type) {
        return Objects.equals(ValidateCodeType.IMAGE, type);
    }

    public void setSecurityProperties(SecurityProperties securityProperties) {
        this.securityProperties = securityProperties;
    }
}
